#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, jsonify, request, current_app
import os
import json

project_bp = Blueprint('project', __name__)

@project_bp.route('/api/project/directory', methods=['GET'])
def get_project_directory():
    """
    获取项目目录结构
    参数：
    - project_id: 项目ID
    - path: 相对于项目根目录的路径，默认为根目录
    """
    try:
        project_id = request.args.get('project_id')
        rel_path = request.args.get('path', '')
        
        if not project_id:
            return jsonify({'error': '缺少项目ID参数'}), 400
            
        # 在实际应用中，应该根据项目ID获取项目根目录
        # 这里使用模拟数据作为示例
        project_root = os.path.join(current_app.config['PROJECTS_DIR'], project_id)
        
        # 构建完整路径
        full_path = os.path.join(project_root, rel_path)
        
        # 安全检查：确保路径不超出项目根目录
        if not os.path.abspath(full_path).startswith(os.path.abspath(project_root)):
            return jsonify({'error': '无效的路径'}), 403
            
        # 检查路径是否存在
        if not os.path.exists(full_path):
            return jsonify({'error': '路径不存在'}), 404
            
        # 获取目录内容
        items = []
        for item in os.listdir(full_path):
            item_path = os.path.join(full_path, item)
            is_dir = os.path.isdir(item_path)
            items.append({
                'name': item,
                'is_directory': is_dir,
                'path': os.path.join(rel_path, item).replace('\\', '/'),
                'icon': 'bi-folder' if is_dir else 'bi-file-earmark-text'
            })
            
        # 按照目录在前，文件在后的顺序排序
        items.sort(key=lambda x: (0 if x['is_directory'] else 1, x['name']))
        
        return jsonify({
            'project_id': project_id,
            'path': rel_path,
            'items': items
        })
        
    except Exception as e:
        current_app.logger.error(f"获取目录结构错误: {str(e)}")
        return jsonify({'error': f'服务器错误: {str(e)}'}), 500